/**
 *
 * @param {*} dbName 数据库名称
 * @param {*} dbVersion 数据库版本
 */
export function openDB(dbName, dbVersion = 1) {
  return new Promise((resolve, reject) => {
    var db;
    var request = indexedDB.open(dbName, dbVersion);

    request.onsuccess = function (event) {
      db = event.target.result;
      resolve(db);
    };

    request.onerror = function (event) {
      console.error("Error initializing IndexedDB:", event.target.error);
      reject(event.target.error);
    };
    request.onupgradeneeded = function (event) {
      db = event.target.result;
      var objectStore = db.createObjectStore("imglist", {
        keyPath: "name",
      });
      objectStore.createIndex("name", "name", { unique: true });
    };
  });
}

/**
 *
 * @param {*} db 数据库实例
 * @param {*} storeName 仓库对象实例（数据表）
 * @param {*} data 数据
 */
export function addData(db, storeName, imageFile) {
  return new Promise((resolve, reject) => {
    // 验证输入
    if (!(imageFile instanceof File)) {
      reject(new Error("输入必须是File对象"));
      return;
    }

    // 创建文件阅读器
    const reader = new FileReader();

    reader.onload = async (event) => {
      try {
        // 准备存储数据
        const imageData = {
          name: imageFile.name,
          type: imageFile.type,
          size: imageFile.size,
          lastModified: imageFile.lastModified,
          data: event.target.result, // 存储为ArrayBuffer
          created: new Date().toISOString(),
        };

        // 开始事务
        const transaction = db.transaction([storeName], "readwrite");
        const store = transaction.objectStore(storeName);
        const addRequest = store.put(imageData);

        const blob = new Blob([imageData.data], { type: imageData.type });
        // 创建 URL
        const url = URL.createObjectURL(blob);

        addRequest.onsuccess = () => {
          resolve({
            name: imageFile.name,
            size: imageFile.size,
            type: imageFile.type,
            url: url,
          });
        };

        addRequest.onerror = (event) => {
          reject(new Error(`存储失败: ${event.target.error}`));
        };
      } catch (error) {
        reject(error);
      }
    };

    reader.onerror = (error) => {
      reject(new Error(`文件读取失败: ${error}`));
    };

    // 读取为ArrayBuffer（更适合存储二进制数据）
    reader.readAsArrayBuffer(imageFile);
  });
}

/**
 *
 * @param {*} db 数据库实例
 * @param {*} storeName 仓库对象实例
 * @param {*} key 查询数据
 * @returns
 */
export function getDataByKey(db, storeName, key) {
  return new Promise((resolve, reject) => {
    const request = db.transaction([storeName]).objectStore(storeName).get(key);
    request.onsuccess = function () {
      const data = request.result;
      if (!data) {
        reject(new Error(`未找到键值为 ${key} 的数据`));
        return;
      }
      // 将 ArrayBuffer 转换为 Blob
      const blob = new Blob([data.data], { type: data.type });
      // 创建 URL
      const url = URL.createObjectURL(blob);
      // 返回包含元数据和 URL 的对象
      resolve({
        name: data.name,
        type: data.type,
        size: data.size,
        lastModified: data.lastModified,
        created: data.created,
        url: url, // 返回图片的 URL
      });
    };
    request.onerror = function () {
      reject(new Error("数据查询失败"));
    };
  });
}

/**
 *
 * @param {*} db 数据库实例
 * @param {*} storeName 仓库对象实例
 * @returns
 */
export function getAllData(db, storeName) {
  return new Promise((resolve, reject) => {
    const request = db.transaction([storeName]).objectStore(storeName).getAll();
    request.onsuccess = function () {
      const data = request.result;
      if (!data || data.length === 0) {
        resolve([]); // 如果没有数据，返回空数组
        return;
      }
      // 处理每个图片数据，生成 URL
      const processedData = data.map((item) => {
        // 将 ArrayBuffer 转换为 Blob
        const blob = new Blob([item.data], { type: item.type });
        // 创建 URL
        const url = URL.createObjectURL(blob);
        // 返回包含元数据和 URL 的对象
        return {
          name: item.name,
          type: item.type,
          size: item.size,
          lastModified: item.lastModified,
          created: item.created,
          url: url, // 返回图片的 URL
        };
      });
      resolve(processedData);
    };
    request.onerror = function () {
      reject(new Error("数据查询失败"));
    };
  });
}
